package com.example.campusforumapi.controller;

import com.example.campusforumapi.entity.User;
import com.example.campusforumapi.service.UserService;
import com.example.campusforumapi.util.JwtUtils;
import com.example.campusforumapi.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController extends BaseController{
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody User user){

        if(userService.findRoleId(user) == 0){
            return Result.error("您还不是管理员身份，请先注册");
        }else{
            User u = userService.login(user);
//        登录成功，生成令牌，下发令牌
            if(u!=null){
                Map<String,Object> claims = new HashMap<>();
                claims.put("userId",u.getUserId());
                claims.put("username",u.getUsername());
                claims.put("avatar",u.getAvatar());
                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }
//            登录失败，返回错误信息
            return  Result.error("用户名密码错误");
        }

    }

}
